//
//  PersonOrderDetailViewController.m
//  TestProject6
//
//  Created by JasonLee on 14/12/11.
//  Copyright (c) 2014年 JasonLee. All rights reserved.
//

#import "PersonOrderDetailViewController.h"
#import "OrderModel.h"
#import "PayViewController.h"
#import "EmptyViewController.h"

#define HeightOfObjectInCell 8

@interface PersonOrderDetailViewController ()<UITableViewDataSource, UITableViewDelegate>{
    UITableView *_tableView;
}

@property (nonatomic,strong)NSDictionary* orderDetailDic;
@property (nonatomic,strong)NSArray* productList;
@property (nonatomic,strong)NSArray* oksnList;
@property (nonatomic,strong)NSDictionary* rePayDic;
@property (nonatomic,strong)NSDictionary* refundOrderDic;

@end


@implementation PersonOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSLog(@"childViewControllers:%@", self.navigationController.childViewControllers);
    NSLog(@"Loading PersonOrderDetailViewController;");
    
    self.navigationItem.title = @"订单详情";
    
    _tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
    //实例化长按手势
    _tableView.scrollEnabled = YES;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [self getOrderDetail];
    UIView *view_navagationBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 65)];
    view_navagationBar.backgroundColor = [Common colorWithRGB:0x18aaf6];
    
    [self.view addSubview:view_navagationBar];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 6;
        case 1:
            return self.oksnList.count;
        case 2:
            return 1;
        default:
            return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
     UILabel *tips = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 10)];
    if (section == 1) {
        tips.font = [UIFont fontWithName:@"Arial" size:10.0];
        tips.textAlignment = UITextAlignmentCenter;
        tips.textColor = [Common colorWithRGB:0xb2b2b2];
        tips.text = @"(点击查看该券二维码)";
    }
    if (_oksnList.count <= 0) {
        return nil;
    }
    return tips;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    if(indexPath.section == 0){
        cell = [tableView dequeueReusableCellWithIdentifier:@"topCell"];
        
        switch (indexPath.row) {
            case 0:
                if(cell == nil){
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"topCell"];
                    cell.textLabel.text = @"订单详情";
                }
                break;
            case 1:
                if(cell == nil){
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downCell1"];
                    cell.textLabel.text = [Common valueForKey:P_NAME dic:_productList[0]];
                }
                break;
            case 2:
                if(cell == nil){
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downCell2"];
                    NSDictionary *orderDetailDic = _orderDetailDic;
                    if (!orderDetailDic) {
                    } else {
                        UILabel *_lbLeft = [[UILabel alloc]initWithFrame:CGRectMake(15, HeightOfObjectInCell, 80, 30)];
                        _lbLeft.text = @"订单号";
                        
                        UILabel *_lbRight = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_lbLeft.frame) + 5, HeightOfObjectInCell, 150, 30)];
                        NSString *orderSN = [Common valueForKey:P_ORDERSN dic:orderDetailDic];
                        _lbRight.text = orderSN;
                        _lbRight.textColor = [UIColor grayColor];
                        _lbRight.font = [UIFont fontWithName:@"Arial" size:14.0f];
                        
                        [cell addSubview:_lbLeft];
                        [cell addSubview:_lbRight];
                    }
                }
                break;
            case 3:
                if(cell == nil){
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downCell2"];
                    UILabel *_lbLeft = [[UILabel alloc]initWithFrame:CGRectMake(15, HeightOfObjectInCell, 100, 30)];
                    _lbLeft.text = @"购买手机号";
                    
                    UILabel *_lbRight = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_lbLeft.frame) + 5, HeightOfObjectInCell, 150, 30)];
                    _lbRight.text = _model.order_phone;
                    _lbRight.textColor = [UIColor grayColor];
                    _lbRight.font = [UIFont fontWithName:@"Arial" size:14.0f];
                    
                    [cell addSubview:_lbLeft];
                    [cell addSubview:_lbRight];
                }
                break;
            case 4:
                if(cell == nil){
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downCell2"];
                    UILabel *_lbLeft = [[UILabel alloc]initWithFrame:CGRectMake(15, HeightOfObjectInCell, 80, 30)];
                    _lbLeft.text = @"付款时间";
                    
                    UILabel *_lbRight = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_lbLeft.frame) + 5, HeightOfObjectInCell, 150, 30)];
                    _lbRight.text = _model.order_datetime;
                    _lbRight.textColor = [UIColor grayColor];
                    _lbRight.font = [UIFont fontWithName:@"Arial" size:14.0f];
                    
                    [cell addSubview:_lbLeft];
                    [cell addSubview:_lbRight];
                }
                break;
            case 5:
                if(cell == nil){
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downCell2"];
                }
                UILabel *_lbLeft = [[UILabel alloc]initWithFrame:CGRectMake(15, HeightOfObjectInCell, 60, 30)];
                _lbLeft.text = @"总价：";
                _lbLeft.textColor = [UIColor grayColor];
                
                UILabel *_lbRight = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_lbLeft.frame) + 5, HeightOfObjectInCell, 150, 30)];
                NSString *string = [NSString stringWithFormat:@"%@元", _model.order_totalPrice];
                _lbRight.text = string;
                _lbRight.font = [UIFont fontWithName:@"Arial" size:14.0f];
        
                UILabel *_lbAction = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
                NSString *refundState = [NSString stringWithFormat:@"%@",[Common valueForKey:P_REFUNDSTATUS dic:_orderDetailDic]];
                NSString *text = [Common valueForKey:P_ORDERSTATUSNAME dic:_orderDetailDic];
                if ([refundState isEqualToString:@"1"]) {
                    text = @"退款中";
                    _model.order_action_color = [UIColor redColor];
                }
                _lbAction.text = text;
                _lbAction.font = [UIFont fontWithName:@"Arial" size:14.0f];
                _lbAction.textColor = _model.order_action_color;
                CGSize titleSize = [text sizeWithFont:_lbAction.font constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
                _lbAction.frame = CGRectMake(cell.bounds.size.width - titleSize.width -10, HeightOfObjectInCell, titleSize.width, 30);
                [cell addSubview:_lbLeft];
                [cell addSubview:_lbRight];
                [cell addSubview:_lbAction];
                break;
            default:
                break;
        }
    }else if (indexPath.section == 1){
        cell = [tableView dequeueReusableCellWithIdentifier:@"downCell"];
        if(cell == nil){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downCell"];
        }
        if (self.oksnList.count > 0) {
            [[cell viewWithTag:1101] removeFromSuperview];
            UILabel *lbLeft = [[UILabel alloc]initWithFrame:CGRectMake(15, HeightOfObjectInCell, 70, 30)];
            lbLeft.text = @"OK码：";
            UILabel *lbMiddle = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lbLeft.frame) + 5, HeightOfObjectInCell, 160, 30)];
            NSDictionary *cellData = _oksnList[indexPath.row];
            lbMiddle.text = [Common valueForKey:P_OKSN dic:cellData];
            lbMiddle.font = [UIFont fontWithName:@"Arial" size:14.0f];
            lbMiddle.textColor = [UIColor grayColor];
            UILabel *lbRight = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lbMiddle.frame) + 5, HeightOfObjectInCell, 60, 30)];
            lbRight.tag = 1101;
            NSString *string = [Common valueForKey:P_STATUSNAME dic:cellData];
            NSString *tempString = [NSString stringWithFormat:@"(%@)", string];
            lbRight.text = tempString;
            lbRight.font = [UIFont fontWithName:@"Arial" size:14.0f];
            lbRight.textColor = [UIColor grayColor];
            [cell.contentView addSubview:lbLeft];
            [cell.contentView addSubview:lbRight];
            [cell.contentView addSubview:lbMiddle];
        }
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"btnCell"];
        if(cell == nil){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"btnCell"];
        }
        if (_orderDetailDic == nil) {
            return cell;
        }
        [cell removeFromSuperview];
        UIView *btnSubmitView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
        btnSubmitView.layer.cornerRadius = 2.0;
        UIButton *btnSubmit = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, btnSubmitView.frame.size.width, btnSubmitView.frame.size.height)];
        int refundStatus = [[Common valueForKey:P_REFUNDSTATUS dic:_orderDetailDic] integerValue];
        int orderStatus = [[Common valueForKey:P_ORDERSTATUS dic:_orderDetailDic] integerValue];
        int confirmStatus = [[Common valueForKey:P_CONFIRMSTATUS dic:_orderDetailDic] integerValue];
        float payCost = [[Common valueForKey:P_ORDERAMOUNT dic:_orderDetailDic] floatValue];
        if (refundStatus == 1 && confirmStatus == 0) {
            [btnSubmit setImage:[UIImage imageNamed:@"tijiaodingdan/tuikuanzhong@2x.png"] forState:UIControlStateNormal];
        } else if (refundStatus == 1 && confirmStatus == 1) {
            [btnSubmit setImage:[UIImage imageNamed:@"tijiaodingdan/tuikuanwancheng@2x.png"] forState:UIControlStateNormal];
        } else if (payCost > 0.00) {
            if (orderStatus == 1) {
                [btnSubmit setImage:[UIImage imageNamed:@"tijiaodingdan/tuikuan@2x.png"] forState:UIControlStateNormal];
                [btnSubmit addTarget:self action:@selector(refundOrder:) forControlEvents:UIControlEventTouchUpInside];
            } else {
                [btnSubmit setImage:[UIImage imageNamed:@"tijiaodingdan/querenzhifu1@2x.png"] forState:UIControlStateNormal];
                [btnSubmit addTarget:self action:@selector(reSubmitOrder:) forControlEvents:UIControlEventTouchUpInside];
            }
        }
        if (orderStatus == 2 || orderStatus ==3){
        } else {
            [btnSubmitView addSubview:btnSubmit];
            [cell addSubview:btnSubmitView];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        NSDictionary *dic = _oksnList[indexPath.row];
        EmptyViewController *QRCodeCtrl = [[EmptyViewController alloc] initWithFrame:self.view.bounds];
        QRCodeCtrl.isOKCoupon = YES;
        QRCodeCtrl.OKCoupon = [Common valueForKey:P_OKSN dic:dic];
        [self.navigationController pushViewController:QRCodeCtrl animated:YES];
    }
}

#pragma mark - Request
- (void)getOrderDetail
{
    NSString *orderSN = _model.order_code;
    [[ProtocolManager shareInstance]getOrderDetail:orderSN target:self selector:@selector(getOrderDetailCallback:)];
}

- (void)reSubmitOrder:(UIButton*)sender
{
    NSString *orderSN = _model.order_code;
    [[ProtocolManager shareInstance] submitOrder:-1 mobile:nil couponCode:nil num:-1 orderPrice:-1 orderSN:orderSN note:nil target:self selector:@selector(submitOrderCallback:)];
}

- (void)refundOrder:(UIButton*)sender
{
    NSString *orderSN = _model.order_code;
    [[ProtocolManager shareInstance] orderRefund:orderSN confirm:NO target:self selector:@selector(refundOrderCallback:)];
}

- (void)orderRefundConfirm
{
    NSString *orderSN = _model.order_code;
    [[ProtocolManager shareInstance] orderRefund:orderSN confirm:YES target:self selector:@selector(orderRefundConfirmCallback:)];
}


#pragma mark - Callback
-(void)getOrderDetailCallback:(NSDictionary*)dic
{
    NSLog(@"==>>PersonOrderDetailViewController-->>getOrderDetailCallback||dic:%@",dic);
    if (dic == nil) {
        return;
    }
    NSDictionary *orderDetailDic = [Common valueForKey:P_RESULT dic:dic];
    self.orderDetailDic = orderDetailDic;
    NSArray *productList = [Common valueForKey:P_PRODUCTLIST dic:dic];
    if ([productList isKindOfClass:[NSArray class]]) {
        self.productList = [NSArray arrayWithArray:productList];
    }
    NSArray *oksnList = [Common valueForKey:P_OKSNLIST dic:dic];
    if ([oksnList isKindOfClass:[NSArray class]]) {
        self.oksnList = [NSArray arrayWithArray:oksnList];
    }
    [_tableView reloadData];
}

- (void)submitOrderCallback:(NSDictionary*)dic
{
    NSLog(@"submitOrderCallback %@", dic)
    if (dic == nil) {
        return;
    }
    _rePayDic = dic;
    NSString *respCode = [Common valueForKey:P_RESPCODE dic:_rePayDic];
    if (![respCode isEqualToString:CODE_HANDLE_SUCCESS]) {
        return;
    }
    
    PayViewController *payViewCtrl = [[PayViewController alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    payViewCtrl.goodsName = _model.order_seller;
    payViewCtrl.totalPrice = [[Common valueForKey:P_ORDERAMOUNT dic:_rePayDic] floatValue];
    payViewCtrl.orderInfo = _rePayDic;
    payViewCtrl.payment_mode = [Common valueForKey:@"paymentMode" dic:_rePayDic];
    payViewCtrl.PersonOrderDetailDeletage = self;
    [self.navigationController pushViewController:payViewCtrl animated:YES];
}

- (void)refreshCell {
    [self getOrderDetail];
}

- (void)refundOrderCallback:(NSDictionary*)dic
{
    NSLog(@"==>>PersonOrderDetailViewController-->>refundOrderCallback||dic:%@",dic);
    if (dic == nil) {
        return;
    }
    _refundOrderDic = dic;
    NSString *refundDesc = [Common valueForKey:P_REFUNDDESC dic:dic];
    UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"退款确认" message:refundDesc delegate:self cancelButtonTitle:@"YES"otherButtonTitles:@"NO",nil];
    [alert show];
}

- (void)orderRefundConfirmCallback:(NSDictionary*)dic
{
    NSLog(@"==>>PersonOrderDetailViewController-->>orderRefundConfirmCallback||dic:%@",dic);
    if (dic == nil) {
        return;
    }
    [_orderDetailDic setValue:[Common valueForKey:P_REFUNDSTATUS dic:dic] forKey:P_REFUNDSTATUS];
    [_oksnList setValue:@"退款" forKey:P_STATUSNAME];
    [_tableView reloadData];
}

#pragma mark - AlertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            [[Common shareInstance] showLoadingViewWithMessage:nil];
            [self orderRefundConfirm];
            break;
            
        default:
            break;
    }
}

@end
